﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServerPlatform.Configuration;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint;
using System.Web;
using KDPWebPart.MapWebPart;
using System.Xml.Serialization;
using System.IO;
using MapEntities;

namespace KDPWebPart
{


    public class SharepointdMapDataProvider : IMapDataProvider
    {
        #region IMapDataProvider Members

        public System.Web.UI.WebControls.WebParts.WebPart GetWebPart(Guid webPartId, string uri, out SPLimitedWebPartManager mng)
        {


            SPSite site = SPContext.Current.Site;
            SPWeb web = site.OpenWeb();
            uri = uri.TrimStart('~', '/');
            SPFile f = web.GetFile(uri);
            SPLimitedWebPartManager mgr = f.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
            mng = mgr;
            try
            {
                string wid = "g_" + webPartId.ToString().Replace('-', '_');
                System.Web.UI.WebControls.WebParts.WebPart wp = mgr.WebParts[wid];
                return wp;
            }
            catch (ArgumentException exc)
            {
                throw new ArgumentException(string.Format("{0} WebPartID @ {1} seems invalid. Msg: {2}\nInner: {3}", webPartId, new Uri(uri).AbsolutePath, exc.Message, exc.InnerException == null ? "" : exc.InnerException.Message));
            }

        }

        public MapEntities.MapDataRequest GetMapData(Guid requestID, string uri)
        {
            SPLimitedWebPartManager mng;
            KDPWebPart.MapWebPart.KDPMapWebPart kpart = (KDPWebPart.MapWebPart.KDPMapWebPart)GetWebPart(requestID, uri, out mng);
            return kpart.GetMapdata();
        }

        #endregion
    }
}
